package com.da.im;

import com.da.im.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author da
 * @time 2023/12/20 上午 9:19
 * websocket服务
 */
@Slf4j
@Component
public class ImServer {

    @Value("${im.port}")
    private Integer port;
    //保存连接用户
    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);

    @PostConstruct
    public void start() {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //添加http编码解码器
                        pipeline.addLast(new HttpServerCodec())
                                //http消息的聚合操作
                                .addLast(new ChunkedWriteHandler())
                                //支持大数据流
                                .addLast(new HttpObjectAggregator(1024 * 64))
                                //websocket
                                .addLast(new WebSocketServerProtocolHandler("/ws"))
                                //自定义的处理器
                                .addLast(new WebSocketHandler());
                    }
                });
        // 绑定端口,开始接收进来的连接
        ChannelFuture future = bootstrap.bind(port);
        log.info("netty服务在{}端口启动了...", port);
    }
}
